package com.css.zfzx.sjcj.modules.hddcWorkRegion.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.*;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.hddcB1GeomorLnOnFractBlt.repository.entity.HddcB1GeomorlnonfractbltEntity;
import com.css.zfzx.sjcj.modules.hddcB1GeomorLnOnFractBlt.viewobjects.HddcB1GeomorlnonfractbltVO;
import com.css.zfzx.sjcj.modules.hddcWorkRegion.repository.HddcWorkregionNativeRepository;
import com.css.zfzx.sjcj.modules.hddcWorkRegion.repository.HddcWorkregionRepository;
import com.css.zfzx.sjcj.modules.hddcWorkRegion.repository.entity.HddcWorkregionEntity;
import com.css.zfzx.sjcj.modules.hddcWorkRegion.service.HddcWorkregionService;
import com.css.zfzx.sjcj.modules.hddcWorkRegion.viewobjects.HddcWorkregionQueryParams;
import com.css.zfzx.sjcj.modules.hddcWorkRegion.viewobjects.HddcWorkregionVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author zyb
 * @date 2020-11-30
 */
@Service
public class HddcWorkregionServiceImpl implements HddcWorkregionService {

	@Autowired
    private HddcWorkregionRepository hddcWorkregionRepository;
    @Autowired
    private HddcWorkregionNativeRepository hddcWorkregionNativeRepository;

    @Override
    public JSONObject queryHddcWorkregions(HddcWorkregionQueryParams queryParams, int curPage, int pageSize,String sort,String order) {
        Page<HddcWorkregionEntity> hddcWorkregionPage = this.hddcWorkregionNativeRepository.queryHddcWorkregions(queryParams, curPage, pageSize, sort, order);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(hddcWorkregionPage);
        return jsonObject;
    }


    @Override
    public HddcWorkregionEntity getHddcWorkregion(String id) {
        HddcWorkregionEntity hddcWorkregion = this.hddcWorkregionRepository.findById(id).orElse(null);
         return hddcWorkregion;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcWorkregionEntity saveHddcWorkregion(HddcWorkregionEntity hddcWorkregion) {
        String uuid = UUIDGenerator.getUUID();
        hddcWorkregion.setUuid(uuid);
        hddcWorkregion.setCreateUser(PlatformSessionUtils.getUserId());
        hddcWorkregion.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        hddcWorkregion.setIsValid("1");
        this.hddcWorkregionRepository.save(hddcWorkregion);
        return hddcWorkregion;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcWorkregionEntity updateHddcWorkregion(HddcWorkregionEntity hddcWorkregion) {
        UpdateUtil.copyNullProperties(hddcWorkregionRepository.findByUuidAndIsValid(hddcWorkregion.getUuid(), "1"), hddcWorkregion);
        hddcWorkregion.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcWorkregion.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcWorkregionRepository.save(hddcWorkregion);
        return hddcWorkregion;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcWorkregions(List<String> ids) {
        List<HddcWorkregionEntity> hddcWorkregionList = this.hddcWorkregionRepository.findAllById(ids);
        if(!PlatformObjectUtils.isEmpty(hddcWorkregionList) && hddcWorkregionList.size() > 0) {
            for(HddcWorkregionEntity hddcWorkregion : hddcWorkregionList) {
                hddcWorkregion.setIsValid("0");
                hddcWorkregion.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcWorkregion.setUpdateTime(new Date());
                this.hddcWorkregionRepository.save(hddcWorkregion);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        return validDictItems;
    }

    @Override
    public void exportFile(HddcWorkregionQueryParams queryParams, HttpServletResponse response) {
        List<HddcWorkregionEntity> yhDisasterEntities = hddcWorkregionNativeRepository.exportYhDisasters(queryParams);
        List<HddcWorkregionVO> list=new ArrayList<>();
        for (HddcWorkregionEntity entity:yhDisasterEntities) {
            HddcWorkregionVO yhDisasterVO=new HddcWorkregionVO();
            BeanUtils.copyProperties(entity,yhDisasterVO);
            list.add(yhDisasterVO);
        }
        EasyPoiExcelUtil.exportExcel(list,"工作区-面","工作区-面",HddcWorkregionVO.class,"工作区-面.xls",response);
    }

    @Override
    public String exportExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<HddcWorkregionVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HddcWorkregionVO.class, params);
            List<HddcWorkregionVO> list = result.getList();
            // Excel条数据
            //int firstList = list.size();
            StringBuilder sb = new StringBuilder();
            //保存
            saveDisasterList(list, sb);
            returnMsg.append("成功导入" + (result.getList().size() ));
            returnMsg.append(sb);
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<HddcWorkregionVO> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    HddcWorkregionVO yhDisasterVO = iterator.next();
                    String error = "";
                    returnMsg.append("第" + yhDisasterVO.getRowNum() + "行" + yhDisasterVO.getErrorMsg() + "<br/>");
                    returnMsg.append(error);
                }
            }
            return returnMsg.toString();
        } catch (Exception e) {

            return "导入失败，请检查数据正确性";
        }
    }

    @Override
    public HddcWorkregionEntity findById(String id) {
        HddcWorkregionEntity hddcWorkregionEntity = hddcWorkregionRepository.findbyId(id);
        return hddcWorkregionEntity;
    }

    /**
     * 批量存入库表并且返回错误数量
     *
     * @param list
     * @param message
     * @return
     */
    public void saveDisasterList(List<HddcWorkregionVO> list, StringBuilder message) {
        for (int i = 0; i < list.size(); i++) {
            HddcWorkregionEntity yhDisasterEntity = new HddcWorkregionEntity();
            HddcWorkregionVO yhDisasterVO = list.get(i);
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(yhDisasterVO, yhDisasterEntity);
            saveHddcWorkregion(yhDisasterEntity);
        }
    }

}
